package com.gimi.cloud.bbp.gateway.service.impl;


import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.bbp.commonService.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gimi.cloud.bbp.common.constant.RedisKeyConstant;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.jwt.Jwt;
import com.gimi.cloud.bbp.gateway.service.CheckTokenService;

/**
 * 校验用户登录token信息Service实现类
 * @author wbj
 * @date 2018-01-20
 * @version  1.0
 */
@Service
public class CheckTokenServiceImpl implements CheckTokenService {
    private final RedisService redisService;
    private static Logger logger = LoggerFactory.getLogger(CheckTokenServiceImpl.class);

    @Autowired
    public CheckTokenServiceImpl(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public ResponseCodeEnum checkToken(String token, String serviceType) {
        logger.info("进入token验证");
        String configKey = "";
        switch (serviceType){
            case "manage":
                configKey = RedisKeyConstant.CONFIG_KEY_MANAGE_USER_TOKEN_RULE;
                break;
            case "merchant":
                configKey = RedisKeyConstant.CONFIG_KEY_MANAGE_USER_TOKEN_RULE;
                break;
            case "app":
                configKey = RedisKeyConstant.CONFIG_KEY_APP_USER_TOKEN_RULE;
                break;
            default:
                break;
        }
        ResponseCodeEnum code = null;
        String secret = "";
        //获取当前配置的信息
        JSONObject userTokenRule = redisService.getJSONObjectConfigByKey(configKey);
        if(null != userTokenRule){
            secret = userTokenRule.getString("jwt_token_secret");
        }else{
            logger.info("用户登录token配置异常");
        }
        Map<String, Object> resultMap = Jwt.validToken(token,secret);
        String state = resultMap.get("state") != null ? resultMap.get("state").toString() : "";
        switch (state){
            case "VALID":
                logger.info("===>令牌校验通过");
                break;
            case "INVALID":
                code = ResponseCodeEnum.SIGNATURE_ERROR;
                logger.error("===>非法的令牌，令牌校验未通过");
                break;
            case "EXPIRED":
                code = ResponseCodeEnum.SIGNATURE_TIMEOUT;
                logger.info("===>过期的令牌，令牌校验未通过");
                break;
            default:
                code = ResponseCodeEnum.SIGNATURE_ERROR;
                logger.error("===>令牌校验失败，校验未通过");
                break;
        }
        logger.info("token验证结束.");
        return code;
    }
}
